---@param player ServerPlayer
---@param skillName string
local removeFangkeSkill = function(player, skillName)
  local room = player.room
  local skill = Fk.skills[skillName]

  local fangke_skills = player:getMark("js_fangke_skills")
  if fangke_skills == 0 then return end
  if not table.contains(fangke_skills, skillName) then
    return
  end
  table.removeOne(fangke_skills, skillName)
  room:setPlayerMark(player, "js_fangke_skills", fangke_skills)

  --[[
  if player:hasSkill(skillName) then -- FIXME: 预亮的bug，预亮技能会导致服务器为玩家直接添加技能
    player:loseSkill(Fk.skills[skillName])
  end
  player:doNotify("LoseSkill", json.encode{ player.id, skillName })

  if skill:isInstanceOf(TriggerSkill) or table.find(skill.related_skills,
    function(s) return s:isInstanceOf(TriggerSkill) end) then
    player:doNotify("LoseSkill", json.encode{ player.id, skillName, true })
  end
  --]]

  player:loseFakeSkill(skill)
  skill:onLose(player)
end


---@param player ServerPlayer
---@param general_name string
local function removeFangke(player, general_name)
  local room = player.room
  local glist = player:getMark("@&js_fangke")
  if glist == 0 then return end
  table.removeOne(glist, general_name)
  room:setPlayerMark(player, "@&js_fangke", #glist > 0 and glist or 0)

  local general = Fk.generals[general_name]
  for _, s in ipairs(general.skills) do
    removeFangkeSkill(player, s.name)
  end
  for _, sname in ipairs(general.other_skills) do
    removeFangkeSkill(player, sname)
  end
end


local pingjian = fk.CreateSkill {
  name = "js__pingjian",

}


pingjian:addEffect(fk.AfterSkillEffect, {
  can_trigger = function(self, _, target, player, data)
    return target == player and player:hasSkill(self) and #player:getTableMark("@&js_fangke") > 0
      and player:getMark("js_fangke_skills") ~= 0 and
      table.contains(player:getMark("js_fangke_skills"), data.name)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, _, target, player, data)
    local room = player.room
    local choices = player:getMark("@&js_fangke")
    local owner = table.find(choices, function (name)
      local general = Fk.generals[name]
      return table.contains(general:getSkillNameList(), data.name)
    end) or "?"
    local choice = choices[1]
    if #choices > 1 then
      local result = player.room:askForCustomDialog(player, self.name,
      "packages/utility/qml/ChooseGeneralsAndChoiceBox.qml", {
        choices,
        {"OK"},
        "#js_lose_fangke:::"..owner,
      })
      if result ~= "" then
        local reply = json.decode(result)
        choice = reply.cards[1]
      end
    end
    removeFangke(player, choice)
    if choice == owner and not player.dead then
      player:drawCards(1, self.name)
    end
  end,
  on_lose = function (self, player)
    if player:getMark("@&js_fangke") ~= 0 then
      for _, g in ipairs(player:getMark("@&js_fangke")) do
        removeFangke(player, g)
      end
    end
  end,
 
})

return pingjian